package com.study.notepad.controller;/*
 @Author Cedar
 @DESCRIPTION 
*/

import com.study.notepad.bean.User;
import com.study.notepad.service.UserService;
import com.study.notepad.service.impl.UserServiceImpl;
import com.study.notepad.util.RandomValueUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    public void query(HttpServletRequest request, HttpServletResponse response) {
        User userById = userService.findUserById(1);
        if (userById == null) {
            System.out.println("没有查询到该用户");
        }
        System.out.println(userById.getName());

    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        User loginUser = userService.login(userName, password);
        if (loginUser != null) {
            String password1 = loginUser.getPassword();
            if ("true".equals(password1)) {
                HttpSession session = request.getSession();
                session.setAttribute("loginUser", loginUser);
                redirect("/userInfo.jsp", request, response);
            } else {
                request.setAttribute("data", "密码输入错误");
                request.setAttribute("userName", userName);
                request.setAttribute("password", password);
                forward("/login.jsp",request,response);
            }
        } else {
            request.setAttribute("data", "用户名不存在");
            request.setAttribute("userName", userName);
            request.setAttribute("password", password);
            forward("/login.jsp",request,response);
        }
    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = null;
        String password = null;
        String passwordConfirm = null;
        String headImg = null;

        List<String> params = new ArrayList<>(3);
        params.add("userName");
        params.add("password");

        Map<String, String> resultMap = uploadImg(request, response, params);
        userName = resultMap.get("userName");
        password = resultMap.get("password");
        headImg = resultMap.get("filePath");

        User userByName = userService.findUserByName(userName);
        if (userByName != null) {
            request.setAttribute("msg", "用户名重复");
            forward("/register.jsp",request,response);
        } else {
            userService.register(userName, password, headImg);
            request.setAttribute("msg", "注册成功，请登录");
            request.setAttribute("url", "/login.jsp");
            forward("/forward.jsp",request,response);
        }
    }

    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = null;
        String userName = null;
        String password = null;
        String headImg = null;

        List<String> params = new ArrayList<>(4);
        params.add("id");
        params.add("userName");
        params.add("password");

        Map<String, String> resultMap = uploadImg(request, response, params);
        id = Integer.parseInt(resultMap.get("id"));
        userName = resultMap.get("userName");
        password = resultMap.get("password");
        headImg = resultMap.get("filePath");

        String msg = "";
        int i = userService.updateUser(id, userName, password, headImg);
        if (i == -1) {
            msg = "用户名已经存在";
        } else if (i == 0) {
            msg = "修改失败";
        } else {
            msg = "修改成功";
        }
        request.setAttribute("msg", msg);
        request.setAttribute("url", "userInfo.jsp");
        forward("/forward.jsp",request,response);
    }


    private Map<String, String> uploadImg(HttpServletRequest request, HttpServletResponse response, List<String> params) {
        Map<String, String> returnMap = new HashMap<>();
        //1、创建磁盘文件项工厂
        //获取web根目录下放置缓存文件的文件夹“temp”的物理路径
        String tempPath = this.getServletContext().getRealPath("/temp");
        //1024*1024为设置文件缓存大小
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024, new File(tempPath));
        //2、创建文件上传的核心类
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置上传文件名称的编码为UTF-8，不设置有可能会出现中文乱码，编码规范要进行设置。
        upload.setHeaderEncoding("UTF-8");
        //判断表单是否是文件上传表单
        boolean multipartContent = upload.isMultipartContent(request);
        if (multipartContent) {
            //是文件上传的表单，解析request获得文件项集合
            List<FileItem> parseRequest = null;
            try {
                parseRequest = upload.parseRequest(request);

                if (parseRequest != null) {
                    for (FileItem item : parseRequest) {
                        //判断是不是普通表单项
                        boolean formField = item.isFormField();
                        if (formField) {
                            //如果是普通表单项
                            String fieldName = item.getFieldName();
                            String fieldValue = null;//对普通表单项的内容进行编码
                            fieldValue = item.getString("UTF-8");
                            //当表单是enctype="multipart/form-data"时，request.getParameter相关的方法都失效，
                            // 所以要用上面的方法获得值
                            //String parameter = request.getParameter("username");//获取不到，失效！

                            for (String param : params) {
                                if (fieldName.equals(param)) {
                                    returnMap.put(param, fieldValue);
                                }
                            }
                        } else {
                            //如果是文件上传项

                            //加入判断文件是否上传，如果不加判断，前台没有选择文件，提交后会报IO空指针异常
                            if (item.getSize() > 0L) {
                                String name = item.getName();

                                if (name == "") {
                                    response.setContentType("text/html;charset=UTF-8");
                                    response.getWriter().write("文件名不能为空");
                                    return null;
                                }

                                String[] nameSplit = name.split("\\.");
                                if (nameSplit.length != 2) {
                                    response.setContentType("text/html;charset=UTF-8");
                                    response.getWriter().write("文件名格式有误");
                                    return null;
                                }
                                String fileName = nameSplit[0];
                                String suffix = nameSplit[1];
                                if (!(suffix.equals("png") || suffix.equals("jpg") || suffix.equals("gif"))) {
                                    response.setContentType("text/html;charset=UTF-8");
                                    response.getWriter().write("文件格式有误");
                                    return null;
                                }

                                fileName = fileName + RandomValueUtil.randomString(6);
                                name = fileName + "." + suffix;
                                String savePath = this.getServletContext().getRealPath("/upload");
                                File file = new File(savePath);
                                if (!file.exists()) {
                                    file.mkdir();
                                }
                                InputStream in = item.getInputStream();
                                OutputStream out = new FileOutputStream(savePath + "/" + name);
                                IOUtils.copy(in, out);
                                in.close();
                                out.close();
                                //删除临时文件
                                item.delete();

                                returnMap.put("filePath", "/upload/" + name);
                            }
                        }
                    }
                }
            } catch (FileUploadException | IOException e) {
                e.printStackTrace();
            }
        }
        return returnMap;
    }
}
